<template>
  <div class="applicationReminderContainer">
    <el-card class="box-card"
             shadow="never">
      <div slot="header"
           class="clearfix">
        <span style="font-weight: 700; font-size: 19px">申请提现</span>
      </div>
      <div class="applicationInfo">
        <div>
          <span>总佣金</span>
          <div>{{
              oemWithdrawalInfo.totalAmount
                ? oemWithdrawalInfo.totalAmount
                : '0'
            }}
          </div>
        </div>
        <div>
          <span>可提现佣金</span>
          <div>{{
              oemWithdrawalInfo.canWithdrawAmount 
                ? oemWithdrawalInfo.canWithdrawAmount
                : '0'
            }}
          </div>
        </div>
        <div>
          <span>可冻结总佣金</span>
          <div>{{
              oemWithdrawalInfo.frozenAmount
                ? oemWithdrawalInfo.frozenAmount
                : '0'
            }}
          </div>
        </div>
        <div>
          <span>已提现总佣金</span>
          <div>{{
              oemWithdrawalInfo.withdrawnTotalAmount 
                ? oemWithdrawalInfo.withdrawnTotalAmount
                : '0'
            }}
          </div>
        </div>
      </div>
    </el-card>
    <!-- 温馨提示 -->
    <el-card class="card"
             shadow="never">
      <el-row :gutter="5">
        <el-col v-bind="styleResponsive ? { lg: 12, md: 24 } : { span: 24 }">
          <div class="prompt">
            <div slot="header"
                 class="clearfix">
              <span style="font-weight: 700; font-size: 19px">温馨提示</span>
            </div>
            <div class="text"> 1.申请提现后，会将佣金打入您申请的账户 </div>
            <div class="text">
              2.如您的收款账户类型为对公账户，请在备注的地方标明为对公账户，否则将影响您的佣金入账
            </div>
            <div class="text">
              3.如您的银行卡来自合作社等，请在备注标明开户行，以免影响佣金到账<br />
            </div>
            <div class="text">
              4.结算方式为按天结算。您的申请可能会分多笔进行到账<br />
            </div>
            <div class="text">
              5.如需开票可点击此处查看开票信息本系统为多通道服务，您的佣金提现申请会自动拆分到对应的服务商核算<br />
              您也可以通过商户管理-查看详情，查询到每个商家的对应的服务商信息。建议您先申请提现，分配到具体服务商后再补充发票。申请提现后，在提现记录中点击查看详情-补充发票，填写发票信息即可
            </div>
          </div>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 12, md: 24 } : { span: 24 }">
          <div class="withdrawalForm">
            <el-form :label-position="labelPosition"
                     :rules="rules"
                     ref="sumbitForm"
                     :model="sumbitForm"
                     class="ruleForm">
              <el-form-item label="提现金额"
                            class="delInput"
                            prop="withdrawalAmount">

                <el-select v-model="sumbitForm.withdrawalAmount"
                           placeholder="请输入申请提现金额">
                  <el-option v-for="item in withdrawalAmountOptions"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                    <span style="float: left">申请提现金额</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.label }}</span>
                  </el-option>
                </el-select>

              </el-form-item>
              <!-- 收款账号 -->
              <el-form-item label="收款账号"
                            prop="receivingAccountId"
                            style="width: 737px">
                <el-select v-model="sumbitForm.receivingAccountId"
                           @visible-change="collectionAccountFn"
                           placeholder="请选择收款账号">
                  <el-option v-for="item in receivingAccountOption"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                    <span style="float: left">{{ item.accountName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>

              <!-- 发票类型 -->

              <el-form-item label="发票类型"
                            prop="invoiceType">
                <el-radio v-model="sumbitForm.invoiceType"
                          label="1">无发票</el-radio>
                <el-radio v-model="sumbitForm.invoiceType"
                          label="2">普通发票</el-radio>
              </el-form-item>
              <!-- 提交发票 -->
              <el-form-item label="发票抬头"
                            v-show="sumbitForm.invoiceType == 2"
                            prop="invoiceUrl">
                <el-upload action="#"
                           ref="pictureUploadInvoiceUrl"
                           list-type="picture-card"
                           :limit="1"
                           :on-exceed="exceedFn"
                           :on-change="
                    (files, fileList) =>
                      handleFileChange(files, fileList, 'invoiceUrl')
                  "
                           :auto-upload="false">
                  <i slot="default"
                     class="el-icon-download">
                    <div style="font-size: 14px; margin-top: 20px"
                         slot="default">点击上传</div>
                  </i>

                  <div slot="file"
                       slot-scope="{ file }">
                    <!-- <iframe src="  https://yunhunjian123.oss-cn-shanghai.aliyuncs.com/invoiceUrl/1692359600097.pdf"
                            height="147px;"
                            width="147px"></iframe> -->
                    <iframe :src="iframeUrl"
                            v-if="useIframePdf"
                            height="147px;"
                            width="147px"></iframe>
                    <img class="el-upload-list__item-thumbnail"
                         v-else
                         :src="file.url"
                         alt="" />
                    <span class="el-upload-list__item-actions">
                      <!-- 图片的预览 -->
                      <span class="el-upload-list__item-preview"
                            @click="handlePictureCardPreview(file)">
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <!-- 图片的下载 -->
                      <span class="el-upload-list__item-delete"
                            @click="handleDownload(file)">
                        <i class="el-icon-download"></i>
                      </span>
                      <!-- 图片的移除 -->
                      <span class="el-upload-list__item-delete"
                            @click="handleRemove(file, 'invoiceUrl')">
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible"
                           width="845px">
                  <iframe :src="iframeUrl"
                          v-if="useIframePdf"
                          height="900px;"
                          width="800px"></iframe>
                  <img width="100%"
                       v-else
                       :src="dialogImageUrl"
                       alt="" />
                </el-dialog>

              </el-form-item>
              <!-- 提交 重置 -->

              <div class="drawer__footer">
                <el-button @click="resetForm('sumbitForm')"
                           type="plain">重置</el-button>
                <el-button type="primary"
                           @click="submitForm('sumbitForm')">提交</el-button>
              </div>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>
<script>
import { getWithdrawalamount } from '@/api/system/serviceProxyConfig'
import axios from 'axios';
import { getToken } from '@/utils/token-util';
import { userOssSignature } from '@/api/creatCenter/material';
import {
  getOemWithdrawalInfo,
  getReceivingAccountList,
  withdrawInsertSelective
} from '@/api/oem/index';
export default {
  name: 'applicationReminder',
  data () {
    const invoiceUrlLogo = (rule, value, callback) => {
      if (this.sumbitForm.invoiceType !== '1') {
        if (!this.sumbitForm.invoiceUrl.length) {
          console.log(!this.sumbitForm.invoiceUrl);

          callback(new Error('请上传图片'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      // 点击次数上限
      frequencyNum: 0,
      // 提现头部查询信息
      oemWithdrawalInfo: {},
      labelPosition: 'top',
      receivingAccountOption: [],
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      disabled: false,
      //图片数量
      listLength: 0,
      useIframePdf: false,
      iframeUrl: '',
      pictureArr: [],
      sumbitForm: {
        // 提现金额
        withdrawalAmount: '',
        // 收款账号
        receivingAccountId: '',
        // 代理标识
        agentIdentification: '1',
        // 发票类型
        invoiceType: '1',
        // oem代理id
        oemId: this.$store.state.user.info.oemId,
        // 发票地址
        invoiceUrl: ''
      },
      //  提现所有的佣金
      withdrawalAmountOptions: [

      ],
      //   最低体现金额
      withdrawalAmount: '',
      rules: {
        receivingAccountId: [
          {
            required: true,
            message: '至少需要选中一个收款账号',
            trigger: 'blur'
          }
        ],

        withdrawalAmount: [
          { required: true, message: '请输入提现金额', trigger: 'blur' },

        ],
        invoiceType: [
          { required: true, message: '请选择发票类型', trigger: 'blur' }
        ],
        //  发票抬头
        invoiceUrl: [
          { required: true, validator: invoiceUrlLogo, trigger: 'change' }
        ]
      }
    };
  },
  // 路由刷新
  activated () {
    this.init();
  },
  computed: {
    // 是否开启响应式布局
    styleResponsive () {
      return this.$store.state.theme.styleResponsive;
    }
  },
  methods: {
    // 申请提现头部数据查询
    async init () {

      const res = await getOemWithdrawalInfo({
        oemId: this.$store.state.user.info.oemId
      });
      //   查询最低体现金额是多少
      const result = await getWithdrawalamount()
      if (result.code == 2000) {
        this.withdrawalAmount = result.data?.withdrawalAmount
          ;
      } else {
        this.$message.error(res.msg);
      }
      if (res.code == 2000) {
        this.withdrawalAmountOptions = []
        this.oemWithdrawalInfo = res.data;
        this.withdrawalAmountOptions.push({
          label: this.oemWithdrawalInfo.canWithdrawAmount ? this.oemWithdrawalInfo.canWithdrawAmount : '0',
          value: this.oemWithdrawalInfo.canWithdrawAmount ? this.oemWithdrawalInfo.canWithdrawAmount : '0',

        })
      } else {
        this.$message.error(res.msg);
      }
    },
    // 下拉款 下拉触发
    async collectionAccountFn (value) {
      console.log(value);
      if (value) {
        const res = await getReceivingAccountList({
          oemId: this.$store.state.user.info.oemId
        });

        console.log(res);
        this.receivingAccountOption = res.data.map((item) => {
          return {
            label: item.receivingAccount,
            value: item.id,
            accountName: '收款账号'
          };
        });
      }
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },
    // 表单重置
    resetForm (formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields();
      });
    },
    // 图片的预览
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = !this.dialogVisible;
    },
    // 图片的下载

    handleDownload (file) {
      window.open(file.url);
    },
    handleRemove (file, removeName) {
      let uploadFiles;
      // 进行判断 对不同的数据进行不同的图片的删除
      if (removeName == 'invoiceUrl') {
        uploadFiles = this.$refs.pictureUploadInvoiceUrl.uploadFiles;
      }

      console.log(this.fileList, file.uid);
      // 获取到该图片的uid 去  this.fileList 去匹配到uid 找到然后去删除掉
      if (this.fileList.length) {
        const uidIndex = this.fileList.findIndex((item, index) => {
          return item.uid == file.uid;
        });
        console.log(uidIndex);
        if (uidIndex !== -1) {
          this.fileList.splice(uidIndex, 1);
        }
        console.log(this.fileList, file.uid);
      }
      for (let i = 0; i < uploadFiles.length; i++) {
        if (uploadFiles[i]['url'] == file.url) {
          uploadFiles.splice(i, 1);
        }
      }

      // 需要把对应上传的图片和 和id 需要删除

      const picIndex = this.pictureArr.findIndex((item) => {
        return item.uid == file.raw.uid;
      });

      this.pictureArr.splice(picIndex, 1);

      console.log(
        this.pictureArr,
        this.fileList,
        this.listLength,
        uploadFiles
      );
    },
    // 提交图片之前的一些限制
    beforeAvatarUpload (file) {
      // const isJPG = file.type === 'image/jpeg';
      console.log(file);
      const isJPG = file.raw.type;
      const isLt2M = file.raw.size / 1024 / 1024 < 2;
      console.log(isJPG);
      const extension1 = file.raw.type === 'image/jpg';
      const extension2 = file.raw.type === 'image/jpeg';
      const extension3 = file.raw.type === 'image/png';
      const extension4 = file.raw.type === 'application/pdf';

      if (!extension1 && !extension2 && !extension3 && !extension4) {
        this.$message.error('请上传jpg 、png、jpeg 、pdf类型图片!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    // 这里对图片上传以后当图片数量大于0则去除校验提示
    handleFileChange (file, fileList, name) {
      if (file.status !== 'ready') return;

      const isPass = this.beforeAvatarUpload(file);
      console.log(isPass);
      if (!isPass) {
        this.handleRemove(file, name);
        return;
      }

      //图片上传后
      console.log(file);
      this.listLength = fileList.length;
      if (name == 'invoiceUrl') {
        this.sumbitForm.invoiceUrl = file.name;
      }

      fileList.forEach((item) => {
        item.imgType = name;
      });
      let files = fileList[fileList.length - 1];
      this.fileList.push(files);
      console.log(file, fileList, this.fileList, name);
      if (this.listLength > 0) {
        // 这里还需要判断一下图片的类型 只有有当前的类型才去除验证
        const fileObject = this.fileList.find((item, index) => {
          return item.imgType == name;
        });

        this.$refs.sumbitForm.clearValidate(fileObject.imgType); //当图片数量大于0则去除校验提示
      }
      this.UploadBj();
    },
    async UploadBj () {
      if (this.fileList.length < 1) {
        console.log('请选择文件后提交');
        this.$message.error('请选择文件后提交');
        return;
      }

      this.disabled = true;
      this.data = await userOssSignature();
      console.log(this.fileList[this.fileList.length - 1]);

      let file = this.fileList[this.fileList.length - 1].raw;
      let imgType = this.fileList[this.fileList.length - 1].imgType;
      let filename = file.name;
      let markIndex = filename.lastIndexOf('.');
      let suffix = filename.substring(markIndex);
      let date = new Date().getTime();
      // 构建请求参数
      let param = new FormData();
      param.append('key', this.data.dir + imgType + '/' + date + suffix);
      param.append('policy', this.data.policy);
      param.append('OSSAccessKeyId', this.data.accessId);
      param.append('success_action_status', '200');
      // param.append("callback",  this.data.callback)     //回调（not)
      param.append('signature', this.data.signature);
      param.append('file', file, file.name);
      param.append('success_action_status', '200');
      let config = {
        headers: {
          'Access-Control-Allow-Origin': '*',
          'x-oss-callback-Authorization': getToken()
        }
      };
      console.log('suffix', suffix);

      let res = await axios.post(this.data.host, param, config);
      let url;
      if (res.status == 200) {
        url = this.data.host + '/' + imgType + '/' + date + suffix;

        console.log('上传图片成功=======', res);
        console.log('this.data.host', url);

        this.fileList.forEach((item) => {
          if (item.raw.type === 'application/pdf') {
            // 使用 iframe 标签
            this.iframeUrl = url;
            // 用 iframe 标签不用img
            this.useIframePdf = true;
          } else {
            this.useIframePdf = false;
          }
        });
        this.pictureArr.push(url);
      } else {
        this.$message.error('上传失败');
      }
      console.log(this.pictureArr, this.fileList, this.listLength);

      this.sumbitForm.invoiceUrl = this.pictureArr[0];
    },
    throttle (fun, timeout) {
      let canRun = true;
      return function () {
        // 如果是true 就不走这
        if (!canRun) {
          this.$message({
            message: '提交太过频繁请稍后在提现',
            type: 'warning'
          });
          return;
        }
        canRun = false;
        setTimeout(() => {
          fun();
          canRun = true;
        }, timeout);
      };
    },
    async withdrawfun () {

      console.log(this.sumbitForm)
      const res = await withdrawInsertSelective(this.sumbitForm);
      console.log(res);
      if (res.code == 2000) {
        // 清楚当前的校验
        this.resetForm('sumbitForm');
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.init()
      } else {
        this.$message.error(res.msg);
        this.init()
      }

    },
    // 提交申请体现
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.frequencyNum < 5) {
            if ((Number(this.oemWithdrawalInfo.canWithdrawAmount)
              ? Number(this.oemWithdrawalInfo.canWithdrawAmount)
              : 0) < Number(this.sumbitForm.withdrawalAmount)) {
              console.log(Number(this.oemWithdrawalInfo.canWithdrawAmount) < Number(this.sumbitForm.withdrawalAmount))
              this.$message.error(`当前可提现佣金为${Number(this.oemWithdrawalInfo.canWithdrawAmount
                ? this.oemWithdrawalInfo.canWithdrawAmount
                : 0)}`);
              //   当点击次数为5的时候提示他操作频繁
              this.frequencyNum++
              return
            }
            //   输入的金额和查询的金额是否相同
            console.log(this.sumbitForm.withdrawalAmount)
            console.log(this.withdrawalAmount)
            if ((Number(this.sumbitForm.withdrawalAmount) < Number(this.withdrawalAmount ? Number(this.withdrawalAmount) : 1))) {
              this.$message.error(`最低可提现佣金为${Number(this.oemWithdrawalInfo.canWithdrawAmount
                ? this.oemWithdrawalInfo.canWithdrawAmount
                : 0)}`);
              this.frequencyNum++
              return
            }
            //  如果是无发票需要置 invoiceUrl为空

            if (this.sumbitForm.invoiceType == '1') {
              this.sumbitForm.invoiceUrl = '';
            }

            const throttleTask = this.throttle(this.withdrawfun, 400);
            throttleTask();


            // 路由跳转到提现记录
            // setTimeout(() => {
            //   this.$router.push('/withdrawalManagement/reflectionRecord');
            // }, 4000);
          } else {
            this.$message.error(`当前提现操作太频繁请稍后在试`);
            setTimeout(() => {
              this.frequencyNum = 0
            }, 20000)
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
/deep/.delInput input::-webkit-outer-spin-button,
/deep/.delInput input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/.delInput input[type='number'] {
  -moz-appearance: textfield;
}
/deep/.el-upload--picture-card {
  line-height: 187px;
}
.applicationReminderContainer {
  min-width: 630px;
  .box-card {
    .clearfix:before,
    .clearfix:after {
      display: table;
      content: '';
    }
    .clearfix:after {
      clear: both;
    }
    .clearfix {
      padding: 0px 0 0 30px;
    }
  }

  .applicationInfo {
    display: flex;
    justify-content: space-evenly;
    span {
      color: #757575;
      font-size: 18px;
    }
    div {
      margin: 7px 0 7px 0;
      color: #1e6ceb;

      font-size: 28px;
    }
  }
  .prompt {
    width: 100%;

    padding: 20px 30px 0 30px;
    box-sizing: border-box;
    overflow: hidden;
    .text {
      margin-top: 30px;
      white-space: wrap;
      margin-bottom: 10px; /* 调整间隔大小 */
      min-width: 490px;
      line-height: 1.5;
    }
  }
  .withdrawalForm {
    padding: 20px 30px 35px 30px;
    box-sizing: border-box;
    width: 100%;
    @media screen and (min-width: 1200px) {
      border-left: 1px solid #ebebeb;
    }

    .ruleForm {
      .el-form-item {
        width: 100% !important;
        .el-select {
          width: 100%;
        }
      }
      .drawer__footer {
        display: flex;
        justify-content: flex-start;
        align-items: center;
      }
    }
  }
}
</style>
